package cn.com.zp.util.database;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;



/***
 * 用于生成实体类
 * @author Administrator
 *
 */
public class GenEntityTool3 {

	private String tablename;

	private String[] colnames; // 列名数组

	private String[] colTypes; // 列名类型数组

	private int[] colSizes; // 列名大小数组

	private int[] colScales; // 类名类型是int类型还是double类型

	private boolean f_util = false; // 是否需要导入包java.util.*

	public GenEntityTool3(String tablename) {
		if(!tablename.equals("")){
			this.tablename = tablename;
		}else{
			System.out.println("表名为空!");
			return;
		}
		Connection conn = DBConnection.getConnection(); // 得到数据库连接
		String strsql = "select * from " + tablename;
		try {
			PreparedStatement pstmt = conn.prepareStatement(strsql);
			pstmt.executeQuery();
			ResultSetMetaData rsmd = pstmt.getMetaData();
			int size = rsmd.getColumnCount(); // 共有多少列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			colScales = new int[size];
			for (int i = 0; i < rsmd.getColumnCount(); i++) {
				colnames[i] = rsmd.getColumnName(i + 1);
				colTypes[i] = rsmd.getColumnTypeName(i + 1);
				colScales[i] = rsmd.getScale(i + 1);
				if (colTypes[i].equalsIgnoreCase("date")
						|| colTypes[i].equalsIgnoreCase("timestamp")) {
					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("number") && colScales[i] == 0) {
					colTypes[i] = "int";
				}
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}
			String content = parse(colnames, colTypes, colSizes);
			try {
				String filePath = "src\\com\\tool\\entity\\"+initcap(tablename) + ".java";
				FileWriter fw = new FileWriter(filePath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
				System.out.println(System.getProperty("user.dir")+"\\"+filePath+"已生成!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.closeConnection(conn);
		}
	}

	/**
	 * 解析处理(生成实体类主体代码)
	 */
	private String parse(String[] colNames, String[] colTypes, int[] colSizes) {
		StringBuffer sb = new StringBuffer();
		sb.append("package com.tool.entity;\r\n\r\n");
		if (f_util) {
			sb.append("import java.util.Date;\r\n");
		}
		sb.append("import javax.persistence.Column; //need add ejb3-persistence.jar\r\n");
		sb.append("import javax.persistence.Entity;\r\n");
		//sb.append("import javax.persistence.Id;\r\n");
		sb.append("import javax.persistence.Table;\r\n\r\n");
		sb.append("@Entity()\r\n");
		sb.append("@Table(name = \"" + this.tablename + "\")\r\n");
		sb.append("public class " + initcap(tablename) + " {\r\n");
		//processAllAttrs(sb);
		processAllMethod(sb);
		sb.append("}");
		return sb.toString();
	}

	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {
		sb.append("\r\n");
		for (int i = 0; i < colnames.length; i++) {
			sb.append("\t@Column(name = \"" + colnames[i] + "\")\r\n");
			sb.append("\tpublic " + OracleType2JavaType(colTypes[i]) + " get"
					+ initcap(colnames[i]) + "() {\r\n");
			sb.append("\t\treturn get(\"" + colnames[i] + "\");\r\n");
			sb.append("\t}\r\n\r\n");

			sb.append("\tpublic void set" + initcap(colnames[i]) + "("
					+ OracleType2JavaType(colTypes[i]) + " " + colnames[i]
					+ ") {\r\n");
			sb.append("\t\tset(\"" + colnames[i] + "\"," + colnames[i] + ");\r\n");
			sb.append("\t}\r\n\r\n");
		}
	}

	/**
	 * 解析输出属性
	 * 
	 * @return
	 */
	@SuppressWarnings("unused")
	private void processAllAttrs(StringBuffer sb) {
		for (int i = 0; i < colnames.length; i++) {
			sb.append("\tprivate " + OracleType2JavaType(colTypes[i]) + " "
					+ colnames[i] + ";\r\n");
		}
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}

	private String OracleType2JavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("int")) {
			return "int";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "float";
		} else if (sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("Varchar2")
				|| sqlType.equalsIgnoreCase("Nvarchar2")
				|| sqlType.equalsIgnoreCase("Long")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("number")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("Date")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("Blob")) {
			return "Blob";
		} else if (sqlType.equalsIgnoreCase("Clob")) {
			return "Clob";
		}
		return null;
	}

	public static void main(String[] args) {
		new GenEntityTool3("register_right_limit");
	}
}
